<template>
  <div class="user-management-container">
    <div class="header">
      <h1>用户管理</h1>
      <el-button type="primary" @click="showAddUserDialog">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名或邮箱搜索"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="searchUsers">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="userList" style="width: 100%" v-loading="loading">
      <el-table-column prop="userId" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="最后登录" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.lastLoginTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            @click="toggleUserStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getUserList, createUser, updateUser, deleteUser as deleteUserApi, updateUserStatus } from '@/api/user';
import { useUserStore } from '@/stores/user';

// 初始化用户store
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const userList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');
const showAddDialog = ref(false);
const isEdit = ref(false);
const userFormRef = ref();

// 用户表单数据
const userForm = reactive({
  userId: null,
  username: '',
  email: '',
  phone: '',
  password: '',
  status: 1
});

// 表单验证规则
const userRules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: isEdit.value ? [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ] : [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}));

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    };
    const response = await getUserList(params);
    // 处理后端返回的PageInfo结构
    if (response.data && response.data.list) {
      userList.value = response.data.list;
      total.value = response.data.total;
    } else {
      userList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const searchUsers = () => {
  currentPage.value = 1;
  fetchUserList();
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  currentPage.value = 1;
  fetchUserList();
};

// 编辑用户
const editUser = (user: any) => {
  isEdit.value = true;
  Object.assign(userForm, user);
  // 编辑模式下清空密码字段
  userForm.password = '';
  showAddDialog.value = true;
};

// 保存用户
const saveUser = async () => {
  if (!userFormRef.value) return;
  
  try {
    await userFormRef.value.validate();
    
    if (isEdit.value) {
      // 更新用户时，不发送password字段
      const updateData = {
        userId: userForm.userId,
        username: userForm.username,
        email: userForm.email,
        phone: userForm.phone,
        status: userForm.status
      };
      await updateUser(updateData);
      ElMessage.success('用户更新成功');
    } else {
      await createUser(userForm);
      ElMessage.success('用户创建成功');
    }
    
    showAddDialog.value = false;
    resetForm();
    fetchUserList();
  } catch (error) {
    ElMessage.error(isEdit.value ? '用户更新失败' : '用户创建失败');
  }
};

// 切换用户状态
const toggleUserStatus = async (user: any) => {
  try {
    const newStatus = user.status === 1 ? 0 : 1;
    await updateUserStatus(user.userId, newStatus);
    ElMessage.success(`用户${newStatus === 1 ? '启用' : '禁用'}成功`);
    fetchUserList();
  } catch (error) {
    ElMessage.error('状态更新失败');
  }
};

// 删除用户
const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await deleteUserApi(user.userId);
    ElMessage.success('用户删除成功');
    fetchUserList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户删除失败');
    }
  }
};

// 显示添加用户对话框
const showAddUserDialog = () => {
  resetForm();
  showAddDialog.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(userForm, {
    userId: null,
    username: '',
    email: '',
    phone: '',
    password: '',
    status: 1
  });
  isEdit.value = false;
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchUserList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchUserList();
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('zh-CN');
};

// 监听对话框关闭
const handleDialogClose = () => {
  resetForm();
};

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token');
  
  if (!token && !userStore.token) {
    return false;
  }
  return true;
};

// 显示登录提示
const showLoginPrompt = async () => {
  try {
    await ElMessageBox.confirm(
      '您尚未登录，无法访问用户管理功能。\n\n默认管理员账户：\n用户名：admin\n密码：admin123\n\n是否前往登录页面？',
      '需要登录',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    // 跳转到登录页面
    window.location.href = '/login';
  } catch {
    // 用户取消，返回上一页或首页
    window.history.back();
  }
};

// 组件挂载时检查登录状态并获取数据
onMounted(async () => {
  // 等待下一个tick确保store完全初始化
  await nextTick();
  
  // 再次检查token状态，确保获取最新值
  const token = localStorage.getItem('token');
  userStore.token = token;
  
  if (checkLoginStatus()) {
    // 已登录，直接获取数据
    await fetchUserList();
  } else {
    // 未登录，显示提示
    ElMessage.warning('请先登录系统');
    await showLoginPrompt();
  }
});
</script>

<style scoped>
.user-management-container {
  padding: 0;
  background: transparent;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: #fff;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header h1 {
  color: #2d3748;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  position: relative;
  padding-left: 20px;
}

.header h1::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 24px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 2px;
}

:deep(.header .el-button--primary) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.header .el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.search-bar {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20px 24px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  gap: 12px;
}

:deep(.search-bar .el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.search-bar .el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.search-bar .el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.search-bar .el-button) {
  border-radius: 12px;
  padding: 12px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.search-bar .el-button--primary) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

:deep(.search-bar .el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-1px);
}

:deep(.el-table) {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

:deep(.el-table th) {
  background: #f8fafc;
  color: #4a5568;
  font-weight: 600;
  border: none;
  padding: 16px 0;
}

:deep(.el-table td) {
  border: none;
  padding: 16px 0;
}

:deep(.el-table tr:hover > td) {
  background: #f8fafc;
}

:deep(.el-table .el-button) {
  border-radius: 8px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-table .el-button--small) {
  padding: 6px 12px;
}

:deep(.el-table .el-button:hover) {
  transform: translateY(-1px);
}

:deep(.el-tag) {
  border-radius: 8px;
  padding: 4px 12px;
  font-weight: 500;
  border: none;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  background: #fff;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

:deep(.el-pagination) {
  gap: 8px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #4a5568;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

.dialog-footer {
  text-align: right;
  padding: 0 24px 24px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.dialog-footer .el-button--primary) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

:deep(.dialog-footer .el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}
</style>